package com.nanjia.boot.product.spu.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.common.enums.StatusEnum;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.product.category.mapper.ProductCategoryMapper;
import com.nanjia.boot.product.category.model.entity.ProductCategory;
import com.nanjia.boot.product.sku.model.query.ProductSkuQuery;
import com.nanjia.boot.product.spu.converter.ProductSpuConverter;
import com.nanjia.boot.product.spu.mapper.ProductSpuMapper;
import com.nanjia.boot.product.spu.model.entity.ProductSpu;
import com.nanjia.boot.product.spu.model.form.ProductSpuForm;
import com.nanjia.boot.product.spu.model.query.ProductSpuQuery;
import com.nanjia.boot.product.spu.model.vo.ProductSpuVO;
import com.nanjia.boot.product.spu.service.ProductSpuService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 商品基础信息(SPU)服务实现类
 *
 * @author 周洋
 * @since 2025-07-07 16:28
 */
@Service
@RequiredArgsConstructor
public class ProductSpuServiceImpl extends ServiceImpl<ProductSpuMapper, ProductSpu> implements ProductSpuService {

    private final ProductSpuConverter productSpuConverter;

    private final ProductCategoryMapper productCategoryMapper;

    /**
     * 获取商品基础信息(SPU)分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<ProductSpuVO>} 商品基础信息(SPU)分页列表
     */
    @Override
    public IPage<ProductSpuVO> getProductSpuPage(ProductSpuQuery queryParams) {
        if (queryParams.getCategoryId() != null) {
            List<Long> allSubCategoryIds = productCategoryMapper.findAllSubCategoryIds(queryParams.getCategoryId());
            if (CollectionUtils.isNotEmpty(allSubCategoryIds)) {
                queryParams.setCategoryIdList(allSubCategoryIds);
                queryParams.setCategoryId(null);
            } else {
                queryParams.setCategoryIdList(Arrays.asList(queryParams.getCategoryId()));
                queryParams.setCategoryId(null);
            }
        }
        Page<ProductSpuVO> pageVO = this.baseMapper.getProductSpuPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取商品基础信息(SPU)表单数据
     *
     * @param id 商品基础信息(SPU)ID
     * @return 商品基础信息(SPU)表单数据
     */
    @Override
    public ProductSpuForm getProductSpuFormData(Long id) {
        ProductSpu entity = this.getById(id);
        return productSpuConverter.toForm(entity);
    }

    /**
     * 新增商品基础信息(SPU)
     *
     * @param formData 商品基础信息(SPU)表单对象
     * @param ipAddr
     * @return 是否新增成功
     */
    @Override
    public boolean saveProductSpu(ProductSpuForm formData, String ipAddr) {

        LambdaQueryWrapper<ProductSpu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ProductSpu::getId);
        List<ProductSpu> list = this.list(queryWrapper);
        int x = 0;
        if (CollectionUtils.isNotEmpty(list)) {
            x = Integer.parseInt(list.get(0).getSpuCode());
        }
//        Map<String, List<String>> map = new HashMap<>();
//        String y[] = new String[]{
//                "/dev-api/api/v1/files/get/20250709/eb52f30345e44808b74c2456bb7091e4.jpg",
//                "/dev-api/api/v1/files/get/20250709/a1ec854f7d3f4d81a4b64737855b8c27.jpg",
//                "/dev-api/api/v1/files/get/20250709/2b98ffbf579b4903822ddbf35159a1f8.jpg",
//                "/dev-api/api/v1/files/get/20250709/839edbdf824e4b929d5a8c0fb83f6bff.jpg",
//                "/dev-api/api/v1/files/get/20250709/5eeff079a4c148c0b8097c7fff29f4ca.jpg",
//                "/dev-api/api/v1/files/get/20250709/be2632b9cfd644e9bf0cf4e3c85d9c87.jpg",
//                "/dev-api/api/v1/files/get/20250709/9c79eff57be74b96aab59831e3072ff3.png",
//                "/dev-api/api/v1/files/get/20250709/d4bb52fb61eb44e99d516aff22b2bb22.jpg"
//        };
//        map.put("detailImages", Arrays.asList(y));
        ProductSpu entity = productSpuConverter.toEntity(formData);
//        entity.setDetailImages(cn.hutool.json.JSONUtil.toJsonStr(map));
        entity.setSpuCode(String.format("%04d", x + 1));
        entity.setCreateBy(SecurityUtils.getUserStrId());
        entity.setCreateIp(ipAddr);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        return this.save(entity);
    }

    /**
     * 更新商品基础信息(SPU)
     *
     * @param id       商品基础信息(SPU)ID
     * @param formData 商品基础信息(SPU)表单对象
     * @param ipAddr
     * @return 是否修改成功
     */
    @Override
    public boolean updateProductSpu(Long id, ProductSpuForm formData, String ipAddr) {
        ProductSpu entity = productSpuConverter.toEntity(formData);
        entity.setId(id);
        entity.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
        entity.setUpdateIp(ipAddr);
        entity.setUpdateTime(LocalDateTime.now());
        return this.updateById(entity);
    }

    /**
     * 删除商品基础信息(SPU)
     *
     * @param ids 商品基础信息(SPU)ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteProductSpus(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的商品基础信息(SPU)数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        List<ProductSpu> list = new ArrayList<>();
        for (Long l : idList) {
            ProductSpu productSpu = new ProductSpu();
            productSpu.setId(l);
            productSpu.setUpdateTime(LocalDateTime.now());
            productSpu.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
            productSpu.setStatus(StatusEnum.DELETE.getValue());
            list.add(productSpu);
        }
        return this.updateBatchById(list, idList.size());
    }

    @Override
    public List<ProductSpu> listSpu(ProductSkuQuery queryParams) {
        if (queryParams == null) {
            return List.of();
        } else {
            Map<String,Object> map = new HashMap<>();
            if (queryParams.getStatus() == null) {
                map.put("status", StatusEnum.ENABLE.getValue());
            } else {
                map.put("status", queryParams.getStatus());
            }

            return this.listByMap(map);
        }

    }
}
